﻿namespace Softserve.Pottery.Infrastructure.Serialization
{
    using System;
    using System.Data.SqlTypes;
    using System.IO;
    using System.Runtime.Serialization;
    using System.Xml;

    public static class XmlSerializationHelper
    {

        /// <summary>
        /// Serializes object to selected XML file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">Path to XML file</param>
        /// <param name="obj">Object to serialize</param>
        public static void XmlSerialize<T>(string fileName, T obj)
        {
            if (obj == null)
            {
                throw new NullReferenceException();
            }

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));
            var setttings = new XmlWriterSettings { Indent = true };

            using (XmlWriter streamWriter = XmlWriter.Create(fileName, setttings))
            {
                serializer.WriteObject(streamWriter, obj);
            }
        }

        /// <summary>
        /// Returns object deserialized from file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName">Path to XML file</param>
        /// <returns>Deserialized object</returns>
        public static T XmlDeserialize<T>(string fileName)
        {
            T obj = default(T);
            var settings = new XmlReaderSettings();
            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            using (XmlReader xmlReader = XmlReader.Create(fileName, settings))
            {
                try
                {
                    obj = (T)serializer.ReadObject(xmlReader);
                    return obj;
                }
                catch {}
            }
            return obj;
        }
    }
}
